package com.itheima.advice;

import com.alibaba.fastjson.JSON;
import com.itheima.annotation.RedisCache2;
import com.itheima.domain.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

/**
 * @author itheima
 * @since 2021-10-26
 */
@Component
@Aspect
public class AopAdvice002 {

    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("execution(public java.util.List<com.itheima.domain.User> com.itheima.service.UserService.getAll())")
    private void pt() {

    }

    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        // 当前运行的方法
        String name = pjp.getSignature().getName();


        Class aClass = pjp.getTarget().getClass();

        Method[] methods = aClass.getMethods();

        for (Method method : methods) {
            System.out.println(method.getName());
            if(name.equals(method.getName())) {

                boolean annotationPresent = method.isAnnotationPresent(RedisCache2.class);

                System.out.println("当前方法" + name + "是否添加了@RedisCache2这个注解" + annotationPresent);

                Object key = redisTemplate.opsForValue().get("key");

                List<User> list = JSON.parseArray("key", User.class);

                if(Objects.nonNull(list) && list.size() > 0) {

                    return list;

                }

                Object proceed = pjp.proceed();

                // 把proceed写入到redis
                // 转json

                redisTemplate.opsForValue().set("key", JSON.toJSONString(proceed));


                return proceed;
            }

        }


        Object proceed = pjp.proceed();


        return proceed;
    }
}
